package com.dlc.shop.jky.common.foreign.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.dto.ShopUserRegisterDto;
import com.dlc.shop.bean.dto.SkuAdminDTO;
import com.dlc.shop.bean.model.*;
import com.dlc.shop.bean.param.OfflineHandleEventAuditParam;
import com.dlc.shop.bean.param.ProductParam;
import com.dlc.shop.bean.vo.ComboProdSkuVO;
import com.dlc.shop.bean.vo.ComboProdVO;
import com.dlc.shop.combo.multishop.service.ComboProdService;
import com.dlc.shop.combo.multishop.service.GiveawayProdService;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.foreign.ipPortMap;
import com.dlc.shop.common.translate.TranslateUtil;
import com.dlc.shop.common.util.BeanUtil;
import com.dlc.shop.config.ShopConfig;
import com.dlc.shop.jky.common.foreign.service.ForeignProductService;
import com.dlc.shop.service.*;
import com.dlc.shop.sys.common.model.ShopEmployee;
import com.dlc.shop.sys.common.service.ShopEmployeeService;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
@Slf4j
public class ForeignProductServicelmpl implements ForeignProductService {

    private final SkuService skuService;
    private final ProductService productService;
    private final BrandService brandService;
    private final ProdParameterService prodParameterService;
    private final ProdExtensionService prodExtensionService;
    private final CategoryService categoryService;
    private final GiveawayProdService giveawayProdService;
    private final ComboProdService comboProdService;
    private final ShopEmployeeService shopEmployeeService;
    private final ShopConfig shopConfig;

    public String getUrlIpPort(){
        ipPortMap ipPortMap = shopConfig.getForeignUrl();
        return ipPortMap.getUrl();
    }

    @Override
    public String save(Long prodId, Long shopId, Long employeeId,OfflineHandleEvent offlineHandleEvent) {
        Product prod = productService.getProductById(prodId);
        if (!Objects.isNull(prod)) {
            //先判断是否为空
            if (prod.getStatus() == -1) {
                //商品状态不正确，请退出重试
                throw new YamiShopBindException("yami.prod.status.error.Please.exit.and.try.again");
            }
        }

        Brand brand = brandService.getByBrandId(prod.getBrandId());
        if (Objects.nonNull(brand)) {
            prod.setBrand(brand);
        }

        List<ProdParameter> prodParameterList = prodParameterService.listParameterByProdId(prodId);
        prod.setProdParameterList(prodParameterList);
        prodExtensionService.getByProdId(prod.getProdId());
        List<Sku> skuList = skuService.listSkuAndSkuStockAndLang(prodId, prod.getMold());
        Integer totalStock = 0;
        Set<Long> skuIds = getIsParticipate(prodId);
        for (Sku sku : skuList) {
            sku.setIsParticipate(skuIds.contains(sku.getSkuId()) ? 1 : 0);
            totalStock += Objects.isNull(sku.getStocks()) ? 0 : sku.getStocks();
        }
        prod.setTotalStocks(totalStock);
        prod.setSkuList(skuList);
        // 平台分类、店铺分类信息
        prod.setCategoryVO(categoryService.getInfo(prod.getCategoryId()));
        if (Objects.nonNull(prod.getShopCategoryId()) && !Objects.equals(prod.getShopCategoryId(), Constant.PLATFORM_SHOP_ID)) {
            prod.setShopCategoryVO(categoryService.getInfo(prod.getShopCategoryId()));
        }

        // ProductParam productParam = new ProductParam();
        prod.setDeliveryMode(null);
        ProductParam productParam = BeanUtil.map(prod, ProductParam.class);
        List<ShopEmployee> shopEmployeeList = shopEmployeeService.listEnableEmployee(prod.getShopId());

        for (ShopEmployee shopEmployee : shopEmployeeList) {
            if (shopEmployee.getType() == 0) {
                productParam.setEmployeeId(employeeId);
                productParam.setEmployeeMobile(shopEmployee.getMobile());
            }
        }

        if (productParam.getSkuList() != null){
            productParam = alimt(productParam);
        }
        //调用 https请求 链接进行同步数据
        // 构建body POST请求
        // 请求的URLp
        String urlIpPort = getUrlIpPort();
        if (urlIpPort == null || urlIpPort.equals("")){
            return "";
        }
        String url = urlIpPort+ "/synchronize/prod/save";

       //HashMap<String, Object> map = new HashMap<>();
       //map.put("productParam",productParam);
       //map.put("offlineHandleEvent",offlineHandleEvent);
        // 构建POST请求
        HttpRequest request = HttpRequest.post(url).header("Content-Type", "application/json") // 设置请求头
                .body(JSON.toJSONString(productParam)); // 设置请求体，这里是一个JSON字符串

        // 发送请求，并接收响应
        HttpResponse response = request.execute();

        // 打印响应的内容
        log.info(request.getUrl() + ";返回结果为：------------》"+response.body());
        return response.body();

    }

    @Override
    public String delete(Long prodId) {
        //调用 https请求 链接进行同步数据
        // 构建body POST请求
        // 请求的URL
        String urlIpPort = getUrlIpPort();
        if (urlIpPort == null || urlIpPort.equals("")){
            return "";
        }
        String url = urlIpPort+ "/synchronize/prod/delete/" + prodId;

        // 构建POST请求
        HttpRequest request = HttpRequest.post(url).header("Content-Type", "application/json"); // 设置请求头
        //.body(JSON.toJSONString(productParam)); // 设置请求体，这里是一个JSON字符串

        // 发送请求，并接收响应
        HttpResponse response = request.execute();

        // 打印响应的内容
        log.info(request.getUrl() + ";返回结果为：------------》"+response.body());
        return response.body();
    }

    @Override
    public String offline(OfflineHandleEvent offlineHandleEvent) {
        //调用 https请求 链接进行同步数据
        // 构建body POST请求
        // 请求的URL
        String urlIpPort = getUrlIpPort();
        if (urlIpPort == null || urlIpPort.equals("")){
            return "";
        }
        String url = urlIpPort+ "/synchronize/prod/offline";

        // 构建POST请求
        HttpRequest request = HttpRequest.post(url).header("Content-Type", "application/json") // 设置请求头
                .body(JSON.toJSONString(offlineHandleEvent)); // 设置请求体，这里是一个JSON字符串

        // 发送请求，并接收响应
        HttpResponse response = request.execute();

        // 打印响应的内容
        log.info(request.getUrl() + ";返回结果为：------------》"+response.body());
        return response.body();
    }

    @Override
    public String auditProd(OfflineHandleEvent offlineHandleEvent) {
        //调用 https请求 链接进行同步数据
        // 构建body POST请求
        // 请求的URL
       // String urlIpPort = getUrlIpPort();
       //if (urlIpPort == null || urlIpPort.equals("")){
       //    return "";
       //}
       //String url = urlIpPort+ "/synchronize/prod/save";

        String save = save(offlineHandleEvent.getHandleId(), offlineHandleEvent.getShopId(), offlineHandleEvent.getHandlerId(), offlineHandleEvent);

        return save;
    }

    @Override
    public String update(ProductParam productParam) {

        //调用 https请求 链接进行同步数据
        // 构建body POST请求
        // 请求的URL
        String urlIpPort = getUrlIpPort();
        if (urlIpPort != null && urlIpPort.equals("")){
            return "";
        }
        String url = urlIpPort+ "/synchronize/prod/update";
        if (productParam.getSkuList() != null){
            productParam = alimt(productParam);
        }
        // 构建POST请求
        HttpRequest request = HttpRequest.post(url).header("Content-Type", "application/json") // 设置请求头
                .body(JSON.toJSONString(productParam)); // 设置请求体，这里是一个JSON字符串

        // 发送请求，并接收响应
        HttpResponse response = request.execute();

        // 打印响应的内容
        log.info(request.getUrl() + ";返回结果为：------------》"+response.body());
        return response.body();
    }

    @Override
    public String deleteList(Long[] ids) {
        //调用 https请求 链接进行同步数据
        // 构建body POST请求
        // 请求的URL
        String urlIpPort = getUrlIpPort();
        if (urlIpPort == null || urlIpPort.equals("")){
            return "";
        }
        String url = urlIpPort+ "/synchronize/prod/batchDelete";

        // 构建POST请求
        HttpRequest request = HttpRequest.post(url).header("Content-Type", "application/json") // 设置请求头
                .body(JSON.toJSONString(ids)); // 设置请求体，这里是一个JSON字符串

        // 发送请求，并接收响应
        HttpResponse response = request.execute();

        // 打印响应的内容
        log.info(request.getUrl() + ";返回结果为：------------》"+response.body());
        return response.body();
    }

    @Override
    public String auditApply(OfflineHandleEventAuditParam offlineHandleEventAuditParam, OfflineHandleEventItem offlineHandleEventItem) {
        //调用 https请求 链接进行同步数据
        // 构建body POST请求
        // 请求的URL
        String urlIpPort = getUrlIpPort();
        if (urlIpPort == null || urlIpPort.equals("")){
            return "";
        }
        String url = urlIpPort+ "/synchronize/prod/auditApply";

        HashMap<Object, Object> map = new HashMap<>();
        map.put("offlineHandleEventAuditParam", offlineHandleEventAuditParam);
        map.put("offlineHandleEventItem", offlineHandleEventItem);
        // 构建POST请求
        HttpRequest request = HttpRequest.post(url).header("Content-Type", "application/json") // 设置请求头
                .body(JSON.toJSONString(map)); // 设置请求体，这里是一个JSON字符串

        // 发送请求，并接收响应
        HttpResponse response = request.execute();

        // 打印响应的内容
        log.info(request.getUrl() + ";返回结果为：------------》"+response.body());
        return response.body();
    }

    @Override
    public String prodOfflineAudit(OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        //调用 https请求 链接进行同步数据
        // 构建body POST请求
        // 请求的URL
        String urlIpPort = getUrlIpPort();
        if (urlIpPort == null || urlIpPort.equals("")){
            return "";
        }
        String url = urlIpPort+ "/synchronize/prod/prodOfflineAudit";

        // 构建POST请求
        HttpRequest request = HttpRequest.post(url).header("Content-Type", "application/json") // 设置请求头
                .body(JSON.toJSONString(offlineHandleEventAuditParam)); // 设置请求体，这里是一个JSON字符串

        // 发送请求，并接收响应
        HttpResponse response = request.execute();

        // 打印响应的内容
        log.info(request.getUrl() + ";返回结果为：------------》"+response.body());
        return response.body();
    }

    @Override
    public String prodStatus(ProductParam productParam) {
        String urlIpPort = getUrlIpPort();
        if (urlIpPort == null || urlIpPort.equals("")){
            return "";
        }
        String url = urlIpPort+ "/synchronize/prod/prodStatus";

        if (productParam.getSkuList() != null){
            productParam = alimt(productParam);
        }
        // 构建POST请求
        HttpRequest request = HttpRequest.post(url).header("Content-Type", "application/json") // 设置请求头
                .body(JSON.toJSONString(productParam)); // 设置请求体，这里是一个JSON字符串

        // 发送请求，并接收响应
        HttpResponse response = request.execute();

        // 打印响应的内容
        log.info(request.getUrl() + ";返回结果为：------------》"+response.body());
        return response.body();
    }

    @Override
    public String batchProdStatus(Long[] ids, Integer status) {

        String urlIpPort = getUrlIpPort();
        if (urlIpPort == null || urlIpPort.equals("")){
            return "";
        }
        String url = urlIpPort+ "/synchronize/prod/batchProdStatus";

        HashMap<String, Object> map = new HashMap<>();
        map.put("ids", ids);
        map.put("status", status);

        // 构建POST请求
        HttpRequest request = HttpRequest.post(url).header("Content-Type", "application/json") // 设置请求头
                .body(JSON.toJSONString(map)); // 设置请求体，这里是一个JSON字符串

        // 发送请求，并接收响应
        HttpResponse response = request.execute();

        // 打印响应的内容
        log.info(request.getUrl() + ";返回结果为：------------》"+response.body());
        return response.body();
    }


    //商品新增，更新都需要更新
    public ProductParam alimt(ProductParam productParam){

        for (SkuAdminDTO skuAdminDTO : productParam.getSkuList()) {
            //翻译sku name
            //String skuName = translate("ru", skuAdminDTO.getSkuName());
            skuAdminDTO.setSkuName(translate("ru", skuAdminDTO.getProperties()));
            String proper = translate("ru", skuAdminDTO.getProperties());
            skuAdminDTO.setProperties(proper);
            skuAdminDTO.setProdName(translate("ru", skuAdminDTO.getProdName()));
            //翻译sku 语音
            List<SkuLang> skuLangList = skuAdminDTO.getSkuLangList();
            for (SkuLang skuLang : skuLangList) {
                skuLang.setProperties(translate("ru", skuLang.getProperties()));
                skuLang.setSkuName(translate("ru", skuLang.getSkuName()));
                skuLang.setProdName(translate("ru", skuLang.getProdName()));
            }
        }
        return productParam;
    }


    public ProductParam productParamSend(Long prodId, Long shopId, Long employeeId) throws Exception {
        Product prod = productService.getProductById(prodId);
        if (!Objects.isNull(prod)) {
            //先判断是否为空
            if (prod.getStatus() == -1) {
                //商品状态不正确，请退出重试
                throw new YamiShopBindException("yami.prod.status.error.Please.exit.and.try.again");
            }
        }

        Brand brand = brandService.getByBrandId(prod.getBrandId());
        if (Objects.nonNull(brand)) {
            prod.setBrand(brand);
        }

        List<ProdParameter> prodParameterList = prodParameterService.listParameterByProdId(prodId);
        prod.setProdParameterList(prodParameterList);
        prodExtensionService.getByProdId(prod.getProdId());
        List<Sku> skuList = skuService.listSkuAndSkuStockAndLang(prodId, prod.getMold());
        Integer totalStock = 0;
        Set<Long> skuIds = getIsParticipate(prodId);
        for (Sku sku : skuList) {
            sku.setIsParticipate(skuIds.contains(sku.getSkuId()) ? 1 : 0);
            totalStock += Objects.isNull(sku.getStocks()) ? 0 : sku.getStocks();
        }
        prod.setTotalStocks(totalStock);
        prod.setSkuList(skuList);
        // 平台分类、店铺分类信息
        prod.setCategoryVO(categoryService.getInfo(prod.getCategoryId()));
        if (Objects.nonNull(prod.getShopCategoryId()) && !Objects.equals(prod.getShopCategoryId(), Constant.PLATFORM_SHOP_ID)) {
            prod.setShopCategoryVO(categoryService.getInfo(prod.getShopCategoryId()));
        }

        // ProductParam productParam = new ProductParam();
        prod.setDeliveryMode(null);
        ProductParam productParam = BeanUtil.map(prod, ProductParam.class);
        productParam.setEmployeeId(employeeId);

        for (SkuAdminDTO skuAdminDTO : productParam.getSkuList()) {
            //翻译sku name
            //String skuName = translate("ru", skuAdminDTO.getSkuName());
            skuAdminDTO.setSkuName(TranslateUtil.text("text", "ru", "zh", skuAdminDTO.getSkuName(), "general"));
            String proper = translate("ru", skuAdminDTO.getProperties());
            skuAdminDTO.setProperties(proper);
            skuAdminDTO.setProdName(translate("ru", skuAdminDTO.getProdName()));
            //翻译sku 语音
            List<SkuLang> skuLangList = skuAdminDTO.getSkuLangList();
            for (SkuLang skuLang : skuLangList) {
                skuLang.setProperties(translate("ru", skuLang.getProperties()));
                skuLang.setSkuName(translate("ru", skuLang.getSkuName()));
                skuLang.setProdName(translate("ru", skuLang.getProdName()));
            }
        }
        return productParam;
    }


    //商品参数翻译
    public static String translate(String targetLanguage, String title) {
        if (title.equals("")){
            return "";
        }
        String skuName = "";
        try {
            //URLEncoder.encode(title.getTitle(),"UTF-8")
            skuName = TranslateUtil.text("text", targetLanguage, "zh", title, "general");
        } catch (Exception e) {
            skuName = title;
        }
        log.info("商品参数翻译：" + title + "翻译结果：" + skuName);
        return skuName;
    }

    @NotNull
    private Set<Long> getIsParticipate(Long prodId) {
        List<GiveawayProd> giveawayProds = giveawayProdService.list(new LambdaQueryWrapper<GiveawayProd>()
                .eq(GiveawayProd::getProdId, prodId)
                .eq(GiveawayProd::getStatus, 1));
        Set<Long> skuIds = giveawayProds.stream().map(GiveawayProd::getSkuId).collect(Collectors.toSet());
        List<ComboProdVO> comboProdList = comboProdService.listComboProdByProdId(prodId);
        for (ComboProdVO comboProd : comboProdList) {
            skuIds.addAll(comboProd.getSkuList().stream().map(ComboProdSkuVO::getSkuId).collect(Collectors.toSet()));
        }
        return skuIds;
    }

}
